package com.zhou.basespringboot2.controller;

import com.zhou.basespringboot2.config.AliyunOssProperties;
import com.zhou.basespringboot2.config.version.ApiVersion;
import com.zhou.basespringboot2.vo.AuthorizeIn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zx
 * @date 2019/7/9 15:52
 */
@ApiVersion(1)
@RequestMapping("{version}/hello")
@RestController
public class HelloWorldController {
    @Autowired
    private AliyunOssProperties properties;

    @RequestMapping("/hello")
    public Map<String, Object> hello() {
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", 200);
        map.put("msg", "success");
        map.put("data", properties);
        return map;
    }

    /**
     * 参数校验
     *
     * @param authorize 入参
     * @param result    校验结果
     */
    @GetMapping("authorize")
    public void authorize(@Valid AuthorizeIn authorize, BindingResult result) {
        validate(result);
        // TODO: 2019/7/9 do something
    }

    /**
     * 判断校验结果
     *
     * @param result
     */
    private void validate(BindingResult result) {
        if (result.hasFieldErrors()) {
            List<FieldError> errorList = result.getFieldErrors();
            errorList.stream().forEach(item -> Assert.isTrue(false, item.getDefaultMessage()));
        }
    }

    /**
     * 统一异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler
    public Map<String, Object> exceptionHandler(Exception e) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("code", 500);
        map.put("msg", "exception");
        map.put("data", e.getMessage());
        e.printStackTrace();
        return map;
    }
}
